//职员管理

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Button, Table, Modal, Row} from 'antd';
import {project,news } from '../value';
import '../css/other.css';
import moment from 'moment';
import {config} from "../config";

import {EditorState, convertToRaw, ContentState} from 'draft-js';
import {Editor} from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const {TextArea}=Input;

class News extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchData: {},
            pagination: {current: 1, pageSize: 10, total: 0},
            data: [],
            currentPageSize: 0,
            pageCount: 0,
            imgUrl: '',
        }
    }

    columns = [
        {
            title: '标题',
            dataIndex: 'news_title'
        },
        {
            title: '简介',
            dataIndex: 'news_summary'
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            render:created_at=>{
                return(
                    <span>{moment(created_at).format('YYYY-MM-DD HH:mm:ss')}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        <Button type="danger" onClick={() => this.handleDeleteProject(data.news_id)}>删除</Button>
                        <EditNumbers news_id={data.news_id} refresh={() => this.handleRefreshAfterUpdate()}></EditNumbers>
                    </span>
                )
            }
        },
    ];

    render() {
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    新闻中心
                </div>
                <SearchLists refresh={()=>this.handleRefreshAfterCreate()} clickSearch={(values) => this.handleGetValue(values)}/>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={(record, index) => index}
                        dataSource={this.state.data}
                        loading={this.state.loading}
                        pagination={this.state.pagination}
                        onChange={this.handleTableChange}
                    />
                </Row>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        this.searchNews({});
    }

    /**
     * 获取搜索条件
     */
    handleGetValue(value) {
        const searchData = {news_title:value};
        this.setState({searchData});
        const param = {
            ...searchData
        };
        this.searchNews(param);
    }

    /**
     * 处理创建后刷新事件
     */
    handleRefreshAfterCreate() {
        const param = {};
        this.searchNews(param);
    }

    /**
     * 处理删除后刷新事件
     */
    handleRefreshAfterDelete() {
        const {searchData} = this.state;
        const param = {
            ...searchData
        };
        this.searchNews(param);
    }

    /**
     * 处理更新后刷新事件
     */
    handleRefreshAfterUpdate() {
        const {searchData} = this.state;
        const param = {
            ...searchData
        };
        this.searchNews(param);
    }

    /**
     * 处理页码、显示数量变化事件
     * @param pagination
     * @param filters
     * @param sorter
     */
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.setState({pagination: pagination1});
    };

    /**
     * 查找新闻列表
     * @param param
     */
    searchNews(param) {
        let _this = this;
        _this.setState({loading: true});
        app.post(news.SEARCH_NEWS, param).then(result => {
            if (result.code === 1) {
                const data=result.data;
                for (let i=0;i<data.length;i++){
                    const content=data[i].news_summary;
                    if(content&&content.length>20){
                        data[i].news_summary=content.substr(0,20)+'...';
                    }
                }
                const pagination={total:data.length,current:1,pageSize:10};
                this.setState({pagination, data: data, loading: false });
            } else {
                app.alert(result.msg, 'success', 2);
                const pagination = {total: 0, current: 0, pageSize: 0};
                this.setState({pagination, data: [], loading: false});
            }
        });
    }

    /**
     * 删除新闻
     * @param id
     */
    handleDeleteProject(id) {
        let _this = this;
        confirm({
            content: '您确定要删除该新闻吗？',
            onOk() {
                app.post(news.DELETE_NEWS, {news_id: id}).then((req) => {
                    if (req.code == '1') {
                        app.alert("删除成功", 'success', 2);
                        _this.handleRefreshAfterDelete();
                    } else {
                        app.alert(req.msg, 'error', 2);
                    }
                })
            },
            onCancel() {
            },
        });
    }
}

//添加职员
class AddNumber extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            editorState: EditorState.createEmpty(), //案例介绍
            newContent: '',
        }
    }

    formItemLayout = {
        labelCol: {span:2},
        wrapperCol: {span:22},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const {editorState} = this.state;
        return (
            <span>
                <Button type='primary' onClick={() => this.showModal(true)} style={{marginLeft: '20px'}}>添加新闻</Button>
                <Modal visible={this.state.visible}
                       maskClosable={false}
                       title="添加新闻"
                       okText={"提交"}
                       width={'1000px'}
                       cancelText={"返回"}
                       onCancel={() => this.showModal(false)}
                       onOk={(e) => this.handleSubmit(e)}
                >
                         <FormItem label={"新闻标题"} {...this.formItemLayout}>
                             {getFieldDecorator('news_title', {
                                 rules: [{required: true, message: '请输入新闻标题'}],
                             })(
                                 <Input
                                     placeholder="请输入新闻标题"/>
                             )}
                         </FormItem>
                    <FormItem label={"新闻简介"} {...this.formItemLayout}>
                             {getFieldDecorator('news_summary', {
                                 rules: [{required: true, message: '请输入新闻简介'}],
                             })(
                                 <TextArea minRows={2}  maxRows={6}
                                     placeholder="请输入新闻简介"/>
                             )}
                         </FormItem>
                    <FormItem label={"内容"} {...this.formItemLayout}>
                         {getFieldDecorator('news_detail')(
                             <div className="setting_regist">
                                 <Editor
                                     editorState={editorState}
                                     toolbarClassName="toolbarClassName1"
                                     wrapperClassName="wrapperClassName1"
                                     editorClassName="editorClassName1"
                                     localization={{
                                         locale: 'zh',
                                     }}
                                     toolbar={{
                                         image: {
                                             uploadCallback: this.uploadImageCallBack,
                                             defaultSize: {
                                                 height: 'auto',
                                                 width: '100%',
                                             }
                                         }
                                     }}
                                     onEditorStateChange={this.onEditorStateChange}
                                 />
                             </div>
                         )}
                    </FormItem>

                </Modal>
            </span>
        )
    }

    //弹出关闭添加框
    showModal(visible) {
        this.setState({visible: visible});
    }

    //提交添加账户
    handleSubmit(e) {
        e.preventDefault();
        let _this = this;
        const {newContent}=this.state;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if(newContent.length<=0){
                    app.alert('请输入新闻内容', 'error', 2);
                    return;
                }
                values.news_detail=newContent;
                app.post(news.CREATE_NEWS, values).then((req) => {
                    if (req.code == 1) {
                        app.alert("添加成功", 'success', 2);
                        _this.setState({visible: false,newContent:'',editorState: EditorState.createEmpty()});
                        _this.props.form.resetFields();
                        _this.props.refresh();
                    } else {
                        app.alert(req.msg, 'error', 2);
                    }
                })
            }
        })
    }

    uploadImageCallBack = (file) => {
        return new Promise(
            (resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('POST', config.fileUrl + project.UPLOAD);
                const data = new FormData();
                data.append('file', file);
                xhr.send(data);
                xhr.addEventListener('load', () => {
                    const response = JSON.parse(xhr.responseText);
                    let imageUrl = config.imgServerUrl + response.data.imgName;
                    resolve({data: {link: imageUrl}});
                });
                xhr.addEventListener('error', () => {
                    const error = JSON.parse(xhr.responseText);
                    reject(error);
                });
            }
        );
    };

    onEditorStateChange = editorState => {
        const finalEditor = draftToHtml(convertToRaw(editorState.getCurrentContent()));
        this.setState({
            newContent:finalEditor,
            editorState,
        });
    };

}

//修改项目
class EditNumber extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            editorState: EditorState.createEmpty(), //案例介绍
            newContent: '',
        }
    }
    formItemLayout = {
        labelCol: {span:2},
        wrapperCol: {span:22},
    };
    render() {
        const {getFieldDecorator} = this.props.form;
        const {editorState} = this.state;
        return (
            <span>
                <Button type='primary' onClick={() => this.showModal(true)} style={{marginLeft: '20px'}}>修改新闻</Button>
                <Modal visible={this.state.visible}
                       maskClosable={false}
                       title="修改新闻"
                       okText={"提交"}
                       width={'1000px'}
                       cancelText={"返回"}
                       onCancel={() => this.showModal(false)}
                       onOk={(e) => this.handleSubmit(e)}
                >
                         <FormItem label={"新闻标题"} {...this.formItemLayout}>
                             {getFieldDecorator('news_title', {
                                 rules: [{required: true, message: '请输入新闻标题'}],
                             })(
                                 <Input
                                     placeholder="请输入新闻标题" />
                             )}
                         </FormItem>
                    <FormItem label={"新闻简介"} {...this.formItemLayout}>
                             {getFieldDecorator('news_summary', {
                                 rules: [{required: true, message: '请输入新闻简介'}],
                             })(
                                 <TextArea minRows={2}  maxRows={6}
                                           placeholder="请输入新闻简介" />
                             )}
                         </FormItem>
                    <FormItem label={"内容"} {...this.formItemLayout} >
                         {getFieldDecorator('news_detail')(
                             <div className="setting_regist">
                                 <Editor
                                     editorState={editorState}
                                     toolbarClassName="toolbarClassName1"
                                     wrapperClassName="wrapperClassName1"
                                     editorClassName="editorClassName1"
                                     localization={{
                                         locale: 'zh',
                                     }}
                                     toolbar={{
                                         image: {
                                             uploadCallback: this.uploadImageCallBack,
                                             defaultSize: {
                                                 height: 'auto',
                                                 width: '100%',
                                             }
                                         }
                                     }}
                                     onEditorStateChange={this.onEditorStateChange}
                                 />
                             </div>
                         )}
                    </FormItem>

                </Modal>
            </span>
        )
    }

    //弹出关闭添加框
    showModal(visible) {
        if(visible){
            this.searchNewsById();
        }
        this.setState({visible: visible});
    }

    //提交添加账户
    handleSubmit(e) {
        e.preventDefault();
        let _this = this;
        const {newContent}=this.state;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if(newContent.length<=0){
                    app.alert('请输入新闻内容', 'error', 2);
                    return;
                }
                values.news_detail=newContent;
                values.news_id=_this.props.news_id;
                app.post(news.UPDATE_NEWS, values).then((req) => {
                    if (req.code == 1) {
                        app.alert("修改成功", 'success', 2);
                        _this.setState({visible: false,newContent:'',editorState: EditorState.createEmpty()});
                        _this.props.form.resetFields();
                        _this.props.refresh();
                    } else {
                        app.alert(req.msg, 'error', 2);
                    }
                })
            }
        })
    }

    uploadImageCallBack = (file) => {
        return new Promise(
            (resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('POST', config.fileUrl + project.UPLOAD);
                const data = new FormData();
                data.append('file', file);
                xhr.send(data);
                xhr.addEventListener('load', () => {
                    const response = JSON.parse(xhr.responseText);
                    let imageUrl = config.imgServerUrl + response.data.imgName;
                    resolve({data: {link: imageUrl}});
                });
                xhr.addEventListener('error', () => {
                    const error = JSON.parse(xhr.responseText);
                    reject(error);
                });
            }
        );
    };

    onEditorStateChange = editorState => {
        const finalEditor = draftToHtml(convertToRaw(editorState.getCurrentContent()));
        this.setState({
            newContent:finalEditor,
            editorState,
        });
    };

    /**
     * 根据新闻Id查找新闻详情
     * @param param
     */
    searchNewsById() {
        let _this = this;
        const news_id=this.props.news_id;
        app.post(news.SEARCH_NEWS_BY_ID, {news_id:news_id}).then(result => {
            if (result.code === 1) {
                const data=result.data;
                const formData={};
                formData['news_title']={value:data.news_title};
                formData['news_summary']={value:data.news_summary};
                _this.props.form.setFields(formData);
                const html=data.news_detail;
                if (html) {
                    let contentBlock = htmlToDraft(html);
                    let contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
                    let editorState = EditorState.createWithContent(contentState);
                    this.setState({
                        editorState
                    });
                    // const finalEditor = draftToHtml(convertToRaw(editorState.getCurrentContent()));
                    // this.state.newContent = finalEditor;
                }
                this.setState({newContent:html});
            } else {
                app.alert(result.msg, 'success', 2);
                this.setState({newContent:'',editorState:EditorState.createEmpty()});
            }
        });
    }

}

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            news_title:''
        }
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div style={{display: 'flex', marginTop: 20, marginBottom: 5}}>
                <div style={{display: 'flex', width: '220px', height: '28px'}}>
                    <div style={{width: 80, height: 28, lineHeight: '28px', color: '#000000'}}>标题：</div>
                    <Input onPressEnter={() => this.handleSearchComplain1()} onChange={(e) => this.handleOnChange(e)}
                           type="text" placeholder="标题"/>
                </div>
                <div style={{display: 'flex', width: '120px', height: '28px', marginLeft: 20}}>
                    <Button type="primary" onClick={() => this.handleSearchComplain1()}>搜索</Button>
                    <AddNumbers refresh={() => this.handleRefreshAfterCreate()}></AddNumbers>
                </div>
            </div>
        )
    };

    componentDidMount() {
    };

    /**
     * 处理账号输入框变化事件
     * @param e
     */
    handleOnChange(e) {
        this.setState({news_title: e.target.value});
    }

    /**
     * 获取搜索条件
     */
    handleSearchComplain1() {
        let {news_title} = this.state;
        this.props.clickSearch(news_title);
    };

    handleRefreshAfterCreate(){
        this.props.refresh();
    }
}

const SearchLists = Form.create()(SearchList);
const AddNumbers = Form.create()(AddNumber);
const EditNumbers = Form.create()(EditNumber);
const NewsList = Form.create()(News);

export default NewsList


